var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

const users = {
  'test@example.com':{
    username: 'testuser',
    password: 'testpassword'
  }
};
// 注册
router.post('/register', async (req, res) => {
    const { email, username, password } = req.body;
    if(users[email]){
      return res.status(400).json({ message: '邮箱已存在' });
    }
    const hashedPassword = await bcrypt.hash(password, 10);

    console.log(hashedPassword);
    // 保存用户信息到数据库
    users[email] = {
      username,
      password: hashedPassword
    };
    res.status(201).json({ message: '注册成功' });
});

// 登录
router.post('/login', async (req, res) => {
    const { email, username, password } = req.body;
    // 从数据库获取用户信息
    const user = users[email];
    if(!user){
      return res.status(400).json({ message: '邮箱不存在' });
    }
    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password);
    if(!isMatch){
      return res.status(400).json({ message: '密码错误' });
    }
    // 生成 JWT 令牌
    const token = jwt.sign({ email, username }, 'your_jwt_secret', {
      expiresIn: '1h'
    });
    res.json({ message: '登录成功', token });
});

// 验证 JWT 令牌
router.get('/profile', (req, res) => {
    // const token = req.headers.authorization?.split(' ')[1];
    const token = req.headers.authorization;
    console.log(token);
    if (!token) {
        return res.status(401).json({ message: '未授权' });
    }
    try {
        const decoded = jwt.verify(token, 'your_jwt_secret');
        res.json({ message: '验证成功', user: decoded });
    } catch (error) {
        res.status(401).json({ message: '无效的令牌' });
    }
});


/* GET users listing. */
router.get('/', function(req, res, next) {
  // #swagger.ignore = true;
  res.send('respond with a resource');
});

module.exports = router;
